package com.hioove.core.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ClassUtils<T> {
    static Logger log = LoggerFactory.getLogger(ClassUtils.class);

    public static Class<?> load(String classReference) {
        try {
            return Class.forName(classReference, false, Thread.currentThread().getContextClassLoader());
        } catch (ClassNotFoundException e) {
            log.error("", e);
        }
        return null;
    }

    public static Class<?> create(String currentClass) {
        try {
            return Class.forName(currentClass, true, Thread.currentThread().getContextClassLoader());
        } catch (ClassNotFoundException e) {
            log.error("", e);
        }
        return null;
    }

    public static <T> T createObj(String currentClassName) {
        try {
            return (T) Class.forName(currentClassName).newInstance();
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    // 获取所有父类
    public static List<Class<?>> allSuperclass(Class<?> currentClass) {
        return Stream.of(currentClass).filter(clazz -> !Objects.isNull(clazz.getSuperclass())).map(clazz -> {
            Builder<ArrayList<Class<?>>> superclass = Builder.of(ArrayList<Class<?>>::new);
            for (Class<?> currentClazz = clazz.getSuperclass(); !currentClazz.equals(Object.class); currentClazz = currentClazz.getSuperclass()) {
                superclass.with(ArrayList::add, currentClazz);
            }
            return superclass.build();
        }).flatMap(Collection::stream).collect(Collectors.toList());
    }

}
